<template>
	<div class="app-container">
		<div v-if="isLearnExam == 0">
			<el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
				<el-form-item label="试卷名称" prop="examName">
					<el-input v-model="queryParams.examName" placeholder="请输入试卷名称" clearable size="small" @keyup.enter.native="handleQuery" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
					<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
				</el-form-item>
			</el-form>

			<el-row :gutter="10" class="mb8">
				<el-col :span="1.5">
					<el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['business:learnExam:add']">新增</el-button>
				</el-col>
				<el-col :span="1.5">
					<el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['business:learnExam:edit']">修改</el-button>
				</el-col>
				<el-col :span="1.5">
					<el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['business:learnExam:remove']">删除</el-button>
				</el-col>
				<el-col :span="1.5">
					<el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['business:learnExam:export']">导出</el-button>
				</el-col>
				<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
			</el-row>

			<el-table v-loading="loading" :data="learnExamList" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" align="center" />
				<!--<el-table-column label="试卷分类" align="center" prop="examType" />-->
				<el-table-column label="试卷名称" align="center" prop="examName" />
				<el-table-column label="是否启用 " align="center" :formatter="isEnabledFormat" prop="isEnabled" />
				<el-table-column label="总分数" align="center" prop="totalScore" />
				<el-table-column label="及格分数" align="center" prop="passScore" />
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
					<template slot-scope="scope">
						<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:learnExam:edit']">修改</el-button>
						<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['business:learnExam:remove']">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
		</div>
		<div v-else>
			<div>
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="isLearnExam = 0">重选试卷</el-button>
				<el-button type="info" @click="addLearnExamQuestion">添加试题</el-button>
			</div>
			<div style="margin-top: 10px;">
				<el-form :inline="true" ref="form" :model="form" :rules="rules" label-width="80px">
					<!--<el-form-item label="试卷分类" prop="examType">
					<el-select style="width:185px" v-model="form.examType" placeholder="请选择试卷分类">
						<el-option label="请选择字典生成" value="" />
					</el-select>
				</el-form-item>-->
					<el-form-item label="试卷名称" prop="examName">
						<el-input v-model="form.examName" placeholder="请输入试卷名称" />
					</el-form-item>
					<el-form-item label="是否启用" prop="isEnabled">
						<el-select v-model="form.isEnabled" placeholder="是否启用" clearable size="small" style="width: 240px">
							<el-option v-for="dict in isEnabledOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
						</el-select>
					</el-form-item>
					<el-form-item label="总分数" prop="totalScore">
						<el-input v-model="form.totalScore" disabled placeholder="请输入总分数" />
					</el-form-item>
					<el-form-item label="及格分数" prop="passScore">
						<el-input v-model="form.passScore" placeholder="请输入及格分数" />
					</el-form-item>
				</el-form>
				<el-table v-loading="loading" :data="learnExamQuestionList" height="700" @selection-change="handleSelectionChange">
					<el-table-column type="selection" width="55" align="center" />
					<!--<el-table-column label="试卷名称" align="center" prop="examName" />-->
					<el-table-column label="试题类型" align="center" prop="questionType" />
					<el-table-column label="试题内容" align="center" prop="questionContent" />
					<el-table-column label="试题选项" align="center" prop="questionOption" />
					<el-table-column label="正确答案" align="center" prop="answer" width="80" />
					<el-table-column label="试题分数" align="center" prop="questionScore" width="80" />
					<el-table-column label="试题提示" align="center" prop="questionRemark" />
					<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
						<template slot-scope="scope">
							<el-button size="mini" type="text" icon="el-icon-edit" @click="updateLearnExamQuestion(scope.row)" v-hasPermi="['business:learnExamQuestion:edit']">修改</el-button>
							<el-button size="mini" type="text" icon="el-icon-delete" @click="deleteLearnExamQuestion(scope.row)" v-hasPermi="['business:learnExamQuestion:remove']">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</div>
		<!-- 添加或修改试题对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
			<div class="form-item">
				<span class="label">题型</span>
				<el-select v-model="formLearnExamQuestion.questionType" placeholder="请选择" size="small" style="width:150px;">
					<el-option v-for="dict in questionTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue">
					</el-option>
				</el-select>
				<span class="label" style="margin-left:20px;">分数</span>
				<el-input-number v-model="formLearnExamQuestion.questionScore" :min="1" :max="100" label="分数"></el-input-number>
			</div>
			<div class="form-item">
				<span class="label">题干</span>
				<div class="item-content">
					<span class="desc">这里填写题目描述</span>
					<el-input size="small" type="textarea" v-model="formLearnExamQuestion.questionContent"></el-input>
				</div>
			</div>
			<div class="form-item">
				<span class="label">选项</span>
				<div class="item-content">
					<span class="desc">单/多选题的选项范围从2到10</span>
					<div>
						<el-radio-group v-model="radio" v-if="formLearnExamQuestion.questionType=='单选题'" class="option-row">
							<div v-for="(obj,index) in questionOptions" style="margin-bottom:10px;">
								<el-radio :label="opt[index]" style="width:100%;">
									<el-input size="small" v-model="obj.option" />
									<i class="el-icon-close remove danger" @click.shop.prevent="deleteOption(obj.index)"></i>
								</el-radio>
							</div>
						</el-radio-group>
						<el-checkbox-group v-model="checked" v-if="formLearnExamQuestion.questionType=='多选题'" class="option-row-checkbox">
							<div v-for="(obj,index) in questionOptions" style="margin-bottom:10px;">
								<el-checkbox :label="opt[index]" style="width:100%;">
									<el-input size="small" v-model="obj.option" />
									<i class="el-icon-close remove danger" @click.shop.prevent="deleteOption(obj.index)"></i>
								</el-checkbox>
							</div>
						</el-checkbox-group>
					</div>
					<el-button type="info" size="small" class="add-option" @click="addOption">+ 添加一个选项</el-button>
				</div>
			</div>
			<div class="form-item">
				<span class="label">提示</span>
				<div class="item-content">
					<span class="desc">这里填写该问题对应的答案解释及知识点说明</span>
					<el-input size="small" type="textarea" v-model="formLearnExamQuestion.questionRemark"></el-input>
				</div>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitLearnExamQuestion">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import { listLearnExam, getLearnExam, delLearnExam, addLearnExam, updateLearnExam } from "@/api/business/learnExam";
	import { validatenull } from '@/utils/validate'
	import { listLearnExamQuestion, getLearnExamQuestion, delLearnExamQuestion, addLearnExamQuestion, updateLearnExamQuestion } from "@/api/business/learnExamQuestion";
	export default {
		name: "LearnExam",
		components: {},
		data() {
			return {
				loading: true, // 遮罩层
				ids: [], // 选中数组
				single: true, // 非单个禁用
				multiple: true, // 非多个禁用
				showSearch: true, // 显示搜索条件
				total: 0, // 总条数
				learnExamList: [], // 试卷表格数据
				title: "", // 弹出层标题
				open: false, // 是否显示弹出层
				queryParams: { // 查询参数
					pageNum: 1,
					pageSize: 10,
					isEnabled: null,
				},
				form: {}, // 表单参数
				rules: { // 表单校验
				},
				isLearnExam: 0,
				isEnabledOptions: [],
				learnExamQuestionList: [],
				formLearnExamQuestion: [],
				questionTypeOptions: [],
				questionOptions: [],
				radio: '',
				checked: [],
				questionOptionSum: 0,
				opt: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
			};
		},
		created() {
			this.getDicts("is_enabled").then(response => {
				this.isEnabledOptions = response.data;
			});
			this.getDicts("question_type").then(response => {
				this.questionTypeOptions = response.data;
			});
			this.getList();
		},
		methods: {
			/** 查询试卷列表 */
			getList() {
				this.loading = true;
				listLearnExam(this.queryParams).then(response => {
					this.learnExamList = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			cancel() { // 取消按钮
				this.open = false;
				this.resetLearnExamQuestion();
			},
			reset() { // 表单重置
				this.form = {
					id: null,
					examType: null,
					examName: null,
					isEnabled: '0',
					totalScore: null,
					passScore: null,
					updateTime: null,
					updateBy: null,
					createTime: null,
					createBy: null,
					delFlag: null
				};
				this.resetForm("form");
			},
			handleQuery() { /** 搜索按钮操作 */
				this.queryParams.pageNum = 1;
				this.getList();
			},
			resetQuery() { /** 重置按钮操作 */
				this.resetForm("queryForm");
				this.handleQuery();
			},
			handleSelectionChange(selection) { // 多选框选中数据
				this.ids = selection.map(item => item.id)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			handleAdd() { /** 新增按钮操作 */
				this.reset();
				this.title = "添加试卷";
				this.isLearnExam = 1
			},
			handleUpdate(row) { /** 修改按钮操作 */
				this.reset();
				const id = row.id || this.ids
				getLearnExam(id).then(response => {
					this.form = response.data;
					this.title = "修改试卷";
					this.isLearnExam = 1
					this.getLearnExamQuestionList()
				});
			},
			getLearnExamQuestionList() {
				this.learnExamQuestionList = []
				listLearnExamQuestion({ // 查询参数
					pageNum: 1,
					pageSize: 1000,
					examId: this.form.id,
				}).then(response => {
					this.learnExamQuestionList = response.rows;
					this.loading = false;
				});
			},
			submitForm() { /** 提交按钮 */
				this.$refs["form"].validate(valid => {
					if(valid) {
						if(this.form.id != null) {
							updateLearnExam(this.form).then(response => {
								this.msgSuccess("修改成功");
								this.getList();
							});
						} else {
							addLearnExam(this.form).then(response => {
								this.msgSuccess("新增成功");
								this.form.id = response.data
								this.getList();
							});
						}
					}
				});
			},
			handleDelete(row) { /** 删除按钮操作 */
				const ids = row.id || this.ids;
				this.$confirm('是否确认删除试卷编号为"' + ids + '"的数据项?', "警告", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				}).then(function() {
					return delLearnExam(ids);
				}).then(() => {
					this.getList();
					this.msgSuccess("删除成功");
				})
			},
			/** 导出按钮操作 */
			handleExport() {
				this.download('business/learnExam/export', {
					...this.queryParams
				}, `试卷.xlsx`)
			},
			addLearnExamQuestion() { /** 新增按钮操作 */
				if(validatenull(this.form.id)) {
					this.msgError("请先保存试卷！");
					return false
				}
				this.resetLearnExamQuestion();
				this.open = true;
				this.title = "添加试题";
			},
			updateLearnExamQuestion(row) { /** 修改按钮操作 */
				this.resetLearnExamQuestion();
				const id = row.id || this.ids
				getLearnExamQuestion(id).then(response => {
					this.formLearnExamQuestion = response.data;
					this.open = true;
					this.title = "修改试题";
					var qos = this.formLearnExamQuestion.questionOption;
					for(var i = 0; i < this.opt.length; i++) { //因为sql的格式是A:XXX,B:XXX 所有要去掉A:这些，并且分割拿到答案，放到数组里
						if(qos.indexOf(this.opt[i]) != -1) {
							var start = qos.indexOf(this.opt[i]) + 2; //获取开始值
							var end = qos.indexOf(this.opt[i + 1]) != -1 ? qos.indexOf(this.opt[i + 1]) : qos.length; //获取结束值
							var qsTemp = qos.substring(start, end); //返回答案
							var obj = {};
							// obj.answer = this.opt[i];
							obj.index = i;
							obj.option = qsTemp;
							this.questionOptions.push(obj);
						}
					}

					this.questionOptionSum = this.questionOptions.length;
					if(this.formLearnExamQuestion.questionType == '单选题') {
						this.radio = this.formLearnExamQuestion.answer;
					} else {
						for(var j = 0; j < this.formLearnExamQuestion.answer.length; j++) {
							this.checked.push(this.formLearnExamQuestion.answer.substring(j, j + 1));
						}
					}
				});
			},
			submitLearnExamQuestion() { /** 提交按钮 */
				if(this.formLearnExamQuestion.questionScore > 100) {
					this.msgError("输入分数不能大于100分！");
					return;
				}
				if(validatenull(this.formLearnExamQuestion.questionContent)) {
					this.msgError("请输入题目内容！");
					return;
				}
				if(this.questionOptions.length < 2) {
					this.msgError("选项内容必须大于2条！");
					return;
				} else {
					for(var i = 0; i < this.questionOptions.length; i++) {
						if(validatenull(this.questionOptions[i].option)) {
							this.msgError("请输入选项内容！");
							return;
						}
					}
				}
				if(this.formLearnExamQuestion.questionType == '单选题') {
					if(validatenull(this.radio)) {
						this.msgError("请选择正确答案！");
						return;
					}
				} else {
					if(this.checked.length == 0) {
						this.msgError("请选择正确答案！");
						return;
					} else if(this.checked.length < 2) {
						this.msgError("请选择两个或以上正确答案！");
						return;
					}
				}

				var optContent = '';
				var aw = '';
				for(var i = 0; i < this.questionOptions.length; i++) {
					if(validatenull(this.questionOptions[i])) {
						continue;
					}
					optContent += this.opt[i] + ':' + this.questionOptions[i].option;
					if(this.formLearnExamQuestion.questionType == '单选题') {
						if(this.opt[i] == this.radio) {
							aw += this.opt[i];
						}
					} else {
						for(var j = 0; j < this.checked.length; j++) {
							if(this.opt[i] == this.checked[j]) {
								aw += this.opt[i];
							}
						}
					}
				}
				this.formLearnExamQuestion.answer = this.strSort(aw);
				this.formLearnExamQuestion.questionOption = optContent;

				if(this.formLearnExamQuestion.id != null) {
					updateLearnExamQuestion(this.formLearnExamQuestion).then(response => {
						this.msgSuccess("修改成功");
						this.open = false;
						this.handleUpdate({
							'id': this.formLearnExamQuestion.examId
						});
					});
				} else {
					addLearnExamQuestion(this.formLearnExamQuestion).then(response => {
						this.msgSuccess("新增成功");
						this.open = false;
						this.handleUpdate({
							'id': this.formLearnExamQuestion.examId
						});
					});
				}
			},
			deleteLearnExamQuestion(row) { /** 删除按钮操作 */
				const ids = row.id || this.ids;
				this.$confirm('是否确认删除试题编号为"' + ids + '"的数据项?', "警告", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				}).then(function() {
					return delLearnExamQuestion(ids);
				}).then(() => {
					this.getList();
					this.msgSuccess("删除成功");
				})
			},
			resetLearnExamQuestion() { // 表单重置
				this.formLearnExamQuestion = {
					id: null,
					examId: this.form.id,
					examName: null,
					questionType: null,
					questionContent: null,
					questionOption: null,
					answer: null,
					questionScore: null,
					questionRemark: null,
					updateTime: null,
					updateBy: null,
					createTime: null,
					createBy: null,
					delFlag: null
				};
				this.questionOptions = []
				this.radio = ''
				this.checked = []
				this.questionOptionSum = 0
				this.resetForm("formLearnExamQuestion");
			},
			addOption() {
				if(this.questionOptionSum > 9) {
					this.$message.error('试题选项已达最大数！')
					return;
				}
				var obj = {};
				obj.index = this.questionOptions.length;
				obj.option = '';
				this.questionOptions.push(obj);
				this.questionOptionSum = this.questionOptions.length;
			},
			deleteOption(content) {
				if(this.questionOptionSum <= 2) {
					this.$message.error('试题选项已达最小数！' + this.questionOptionSum)
					return;
				}
				this.questionOptionSum = this.questionOptionSum - 1;
				this.questionOptions.splice(content, 1); //删除选项
				for(var i = 0; i < this.questionOptions.length; i++) {
					this.questionOptions[i].index = i + '';
				}
				for(var i = 0; i < this.opt.length; i++) {
					if(this.formLearnExamQuestion.questionType == '单选题') {
						if(this.opt[i] == this.radio) {
							if(i + 1 > this.questionOptions.length) {
								this.radio = this.opt[i - 1]
							}
						}
					} else {
						for(var j = 0; j < this.checked.length; j++) {
							for(var i = 0; i < this.opt.length; i++) {
								if(this.opt[i] == this.checked[j]) {
									if(i + 1 > this.questionOptions.length) {
										this.$message.error('进来了！' + i + j)
										this.checked[j] = this.opt[i - 1]
									}
								}
							}
						}
					}
				}
				//删除选择的答案
				if(this.formLearnExamQuestion.questionType == '单选题') {
					if(this.opt[content] == this.radio) {
						this.radio = "";
					}
				} else {
					for(var i = this.checked.length; i >= 0; i--) {
						if(this.opt[content] == this.checked[i]) {
							this.checked.splice(i, 1); //删除选中值
						}
					}
				}
			},
			isEnabledFormat(row, column) {
				return this.selectDictLabel(this.isEnabledOptions, row.isEnabled);
			},
		}
	};
</script>

<style lang="scss">
	$ratio:16;
	.question-input {
		.el-textarea__inner {
			border: none;
			height: 80/$ratio*1em;
		}
	}
	
	.my-dialog {
		.el-dialog__body {
			padding: 0;
		}
	}
	
	.el-checkbox__label,
	.el-radio__label {
		width: 100%;
	}
</style>
<style lang="scss" scoped>
	$ratio:16;
	.container {
		background: #FFFFFF;
	}
	
	.form-item {
		margin-bottom: 15px;
		display: flex;
		flex-direction: row;
	}
	
	.item-content {
		display: flex;
		flex-direction: column;
		flex: 1;
	}
	
	.label {
		padding: 5px 15px;
		background: #409eff;
		color: #ffffff;
		height: 30px;
		line-height: 20px;
		margin-right: 12px;
	}
	
	.desc {
		font-size: 14px;
		color: #adabab;
		height: 30px;
		line-height: 30px;
		margin-bottom: 5px;
	}
	
	.add-option {
		margin: 0 24px;
	}
	
	.hide-remove {
		visibility: hidden;
	}
	
	.remove {
		cursor: pointer;
		margin-left: 10px;
		font-size: 16px;
	}
	
	.content {
		overflow-y: auto;
		height: calc(100vh - 5.5em);
	}
	
	.option-row {
		width: 100%;
		padding-right: 48px;
	}
	
	.option-row-checkbox {
		width: 100%;
		padding-right: 38px;
	}
	
	.question-category,
	.question-score,
	.question-title,
	.question-tips {
		padding: 0 15/$ratio*1em;
		height: 50/$ratio*1em;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		border-bottom: 1px solid #f5f5f5;
	}
	
	.question-label {
		color: #4A4A4A;
		width: 50/$ratio*1em;
		font-size: 16/$ratio*1em;
	}
	
	.question-value {
		color: #9B9B9B;
		font-size: 14/$ratio*1em;
	}
	
	.question-input {
		flex: 1;
	}
	
	.question-title {
		height: 112/$ratio*1em;
	}
	
	.question-tips {
		height: 112/$ratio*1em;
		margin-bottom: 50/$ratio*1em;
	}
	
	.question-option {
		padding: 0 15/$ratio*1em;
		border-bottom: 1px solid #f5f5f5;
		.question-option-remark {
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: space-between;
			.tips {
				font-size: 14px;
				color: #9B9B9B;
			}
		}
		.option-h {
			height: 40/$ratio*1em;
			line-height: 40/$ratio*1em;
		}
	}
	
	.question-option-list {
		ul {
			list-style: none;
			margin: 0;
			padding: 0;
			li {
				font-size: 14/$ratio*1em;
				padding: 15/$ratio*1em 0;
				border-bottom: 1px solid #f5f5f5;
			}
		}
		.add-button {
			margin: 0 26/$ratio*1em;
			margin-bottom: 20/$ratio*1em;
			padding: 10/$ratio*1em 0;
			background: #D7D7D7;
			text-align: center;
			font-size: 14px;
			color: #ffffff;
			border-radius: 5/$ratio*1em;
		}
	}
	
	.arrow {
		margin-left: 5/$ratio*1em;
	}
	
	.primary {
		color: #409EFF;
	}
	
	.danger {
		color: #f56c6c;
	}
	
	.success {
		color: #67c23a;
	}
	
	.footer-div {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		z-index: 99;
	}
	
	.footer-desktop {
		text-align: center;
		width: 100%;
	}
	
	.footer {
		display: flex;
		flex-direction: row;
	}
	
	.footer-calcel {
		font-size: 16/$ratio*1em;
		color: #4A4A4A;
		background-color: #ffffff;
		border-top: 1px solid #f5f5f5;
		flex: 1;
		text-align: center;
		height: 44/$ratio*1em;
		line-height: 44/$ratio*1em;
	}
	
	.footer-save {
		font-size: 16/$ratio*1em;
		color: #ffffff;
		background-color: #409EFF;
		border-top: 1px solid #409EFF;
		flex: 1;
		text-align: center;
		height: 44/$ratio*1em;
		line-height: 44/$ratio*1em;
	}
	
	.dialog-footer {
		text-align: center;
		padding-bottom: 20/$ratio*1em;
	}
	
	.dialog-ul {
		list-style: none;
		margin: 0;
		padding: 0;
		li {
			padding: 20/$ratio*1em 0;
			margin: 0 20/$ratio*1em;
			border-top: 1px solid #f5f5f5;
		}
	}
	
	.dialog-input {
		padding: 30/$ratio*1em 20/$ratio*1em;
	}
</style>